<template>
  <div class="product-config">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span>产品参数配置</span>
          <el-button type="primary" @click="handleAdd">新增配置</el-button>
        </div>
      </template>

      <!-- 参数配置表格 -->
      <el-table
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="参数名称" min-width="150" />
        <el-table-column prop="key" label="参数键" width="150" />
        <el-table-column prop="type" label="参数类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getParamTypeTag(row.type)">
              {{ getParamTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="defaultValue" label="默认值" min-width="120" />
        <el-table-column prop="options" label="可选值" min-width="200">
          <template #default="{ row }">
            <template v-if="row.type === 'select' || row.type === 'checkbox'">
              <el-tag
                v-for="option in row.options"
                :key="option.value"
                class="option-tag"
              >
                {{ option.label }}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="required" label="是否必填" width="100">
          <template #default="{ row }">
            <el-tag :type="row.required ? 'danger' : 'info'">
              {{ row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="参数说明" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                link
                type="primary"
                @click="handleEdit(row)"
              >编辑</el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(row)"
              >删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键" prop="key">
          <el-input v-model="formData.key" placeholder="请输入参数键" />
        </el-form-item>
        <el-form-item label="参数类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择参数类型" style="width: 100%">
            <el-option label="文本" value="text" />
            <el-option label="数字" value="number" />
            <el-option label="选择器" value="select" />
            <el-option label="多选框" value="checkbox" />
            <el-option label="日期" value="date" />
            <el-option label="时间" value="time" />
            <el-option label="日期时间" value="datetime" />
            <el-option label="开关" value="switch" />
            <el-option label="滑块" value="slider" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认值" prop="defaultValue">
          <el-input v-model="formData.defaultValue" placeholder="请输入默认值" />
        </el-form-item>
        <el-form-item
          label="可选值"
          prop="options"
          v-if="formData.type === 'select' || formData.type === 'checkbox'"
        >
          <div class="options-container">
            <div
              v-for="(option, index) in formData.options"
              :key="index"
              class="option-item"
            >
              <el-input
                v-model="option.label"
                placeholder="选项名"
                style="width: 180px"
              />
              <el-input
                v-model="option.value"
                placeholder="选项值"
                style="width: 180px"
              />
              <el-button
                type="danger"
                circle
                @click="removeOption(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button type="primary" @click="addOption">添加选项</el-button>
          </div>
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-switch v-model="formData.required" />
        </el-form-item>
        <el-form-item label="参数说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入参数说明"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="验证规则" prop="rules" v-if="formData.type === 'text' || formData.type === 'number'">
          <div class="rules-container">
            <div class="rule-item" v-if="formData.type === 'text'">
              <el-checkbox v-model="formData.rules.required">必填</el-checkbox>
              <el-input-number
                v-model="formData.rules.minLength"
                :min="0"
                placeholder="最小长度"
              />
              <span>-</span>
              <el-input-number
                v-model="formData.rules.maxLength"
                :min="0"
                placeholder="最大长度"
              />
              <el-input
                v-model="formData.rules.pattern"
                placeholder="正则表达式"
                style="width: 180px"
              />
            </div>
            <div class="rule-item" v-if="formData.type === 'number'">
              <el-checkbox v-model="formData.rules.required">必填</el-checkbox>
              <el-input-number
                v-model="formData.rules.min"
                placeholder="最小值"
              />
              <span>-</span>
              <el-input-number
                v-model="formData.rules.max"
                placeholder="最大值"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import axios from 'axios'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const formData = reactive({
  name: '',
  key: '',
  type: 'text',
  defaultValue: '',
  options: [],
  required: false,
  description: '',
  sort: 0,
  rules: {
    required: false,
    minLength: null,
    maxLength: null,
    pattern: '',
    min: null,
    max: null
  }
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入参数名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  key: [
    { required: true, message: '请输入参数键', trigger: 'blur' },
    { pattern: /^[A-Za-z][A-Za-z0-9_]*$/, message: '以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择参数类型', trigger: 'change' }
  ]
}

// 获取参数类型标签样式
const getParamTypeTag = (type) => {
  const types = {
    text: '',
    number: 'success',
    select: 'warning',
    checkbox: 'warning',
    date: 'info',
    time: 'info',
    datetime: 'info',
    switch: 'primary',
    slider: 'primary'
  }
  return types[type] || ''
}

// 获取参数类型名称
const getParamTypeName = (type) => {
  const types = {
    text: '文本',
    number: '数字',
    select: '选择器',
    checkbox: '多选框',
    date: '日期',
    time: '时间',
    datetime: '日期时间',
    switch: '开关',
    slider: '滑块'
  }
  return types[type] || type
}

// 获取配置列表
const getConfigList = async () => {
  loading.value = true
  try {
    const res = await axios.get('/api/product/config/list', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res.data.code === 200) {
      tableData.value = res.data.data.list
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('获取配置列表失败', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增配置'
  Object.assign(formData, {
    name: '',
    key: '',
    type: 'text',
    defaultValue: '',
    options: [],
    required: false,
    description: '',
    sort: 0,
    rules: {
      required: false,
      minLength: null,
      maxLength: null,
      pattern: '',
      min: null,
      max: null
    }
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑配置'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该配置吗？删除后不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await axios.post('/api/product/config/delete', { id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getConfigList()
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  })
}

// 添加选项
const addOption = () => {
  formData.options.push({
    label: '',
    value: ''
  })
}

// 移除选项
const removeOption = (index) => {
  formData.options.splice(index, 1)
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const url = formData.id ? '/api/product/config/update' : '/api/product/config/add'
        const res = await axios.post(url, formData)
        if (res.data.code === 200) {
          ElMessage.success('操作成功')
          dialogVisible.value = false
          getConfigList()
        }
      } catch (error) {
        console.error('操作失败', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getConfigList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getConfigList()
}

onMounted(() => {
  getConfigList()
})
</script>

<style scoped>
.product-config {
  padding: 20px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.option-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.options-container {
  .option-item {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
    align-items: center;
  }
}

.rules-container {
  .rule-item {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
    align-items: center;
  }
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 